package publish

import (
	"encoding/json"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"time"
)

type Message[T any] struct {
	Topic string
	Data  T
}

func NewMqttPublishClient() mqtt.Client {
	opts := mqtt.NewClientOptions().AddBroker("tcp://localhost:1883").
		SetUsername("go-test-publish").
		SetPassword("123456")

	opts.SetKeepAlive(60 * time.Second)
	opts.SetPingTimeout(1 * time.Second)
	c := mqtt.NewClient(opts)
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	return c
}

func Send[T any](msg Message[T], client mqtt.Client) {

	marshal, _ := json.Marshal(msg.Data)

	token := client.Publish(msg.Topic, 0, false, string(marshal))
	token.Wait()
}
